<?php

/**
 * This is the model class for table "mb_pages".
 *
 * The followings are the available columns in table 'mb_pages':
 * @property string $pageId
 * @property string $pageParent
 * @property string $pageType
 * @property integer $pageItemId
 * @property string $pageUrl
 * @property string $pageTitle
 * @property string $pageContentShort
 * @property string $pageContentFull
 * @property string $pageImages
 * @property integer $pageActive
 * @property string $pageAuthor
 * @property integer $pageSort
 * @property string $pageAction
 * @property integer $pageSource
 * @property string $pageDescription
 */
class Page extends CActiveRecord {

    public $actions = array('actions' => 'bonus/view', 'news' => 'news/view', 'articles' => 'page', 'info' => 'page', 'brand' => 'list/brand', 'model' => 'list/model', 'category' => 'list', 'list' => 'list', 'servcenter' => 'service/view', 'service' => 'uslugi/view', 'contact' => 'contact');

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{pages}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
        return array(
            array('pageUrl, pageTitle, pageAction', 'required'),
            array('pageUrl', 'unique'),
            array('pageFullTitle, pageItemId, pageDescription', 'default'),
            array('pageImages', 'file', 'allowEmpty' => true, 'types' => 'jpg,bmp,jpeg,gif,png'),
            array('pageActive, pageSort', 'numerical', 'integerOnly' => true),
            array('pageParent, pageAuthor', 'length', 'max' => 11),
            array('pageType', 'length', 'max' => 50),
            array('pageUrl, pageTitle, pageImages, pageAction', 'length', 'max' => 255),
            array('pageContentShort, pageContentFull, pageDescription', 'safe'),
            // The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
            array('pageId, pageParent, pageType, pageUrl, pageTitle, pageContentShort, pageContentFull, pageImages, pageActive, pageAuthor, pageSort, pageAction, pageSource, pageDescription', 'safe', 'on' => 'search'),
        );
    }

    public function getProductCategory() {
        $sql = 'select			
			b."pageId" as "id",
			(SELECT "pageTitle" FROM mb_pages c WHERE c."pageId" = b."pageParent") || \' \' || b."pageTitle" as "title"
			FROM mb_pages b
			WHERE 
			b."pageType"=\'brand\' AND b."pageActive" = \'1\' ORDER BY b."pageSort"';
        return json_encode(Yii::app()->db->createCommand($sql)->queryAll(true), 1);
    }

//	public function getPages() {
//
//		$query = "SELECT p.pageId,p.pageParent, p.pageTitle FROM {{pages}} p WHERE p.pageType <> 'model';";
//		$models = Yii::app()->db->createCommand( $query )->queryAll( true );
//		
//		foreach ($models as $model)
//			$array[$model['pageId']] = array('pageId' => $model['pageId'], 'pageTitle' => $model['pageTitle'], 'pageParent' => $model['pageParent']);
//		return $array;
//	}
//
//	function recursive($parent, $array, $level = 0) {
//		$itemsFormatted = array();
//		foreach ($array as $key => $value) {
//			if ($value['pageParent'] == $parent) {
//				$itemsFormatted[$value['pageId']] = str_repeat('&nbsp;&nbsp;', $level) . $value['pageTitle'];
//				$itemsFormatted = $itemsFormatted + $this->recursive($key, $array, $level + 1);
//			}
//		}
//		return $itemsFormatted;
//	}

    public function getDropdownItems($level = 0) {
        $query = "SELECT \"pageId\", \"pageTitle\" FROM {{pages}} WHERE \"pageParent\" = 0";
        $models = Yii::app()->db->createCommand($query)->queryAll(true);
        foreach ($models as $model)
            $array[$model['pageId']] = $model['pageTitle'];
        return $array;
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
        return array();
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'pageId' => 'ID',
            'pageParent' => 'Родитель',
            'pageType' => 'Тип страницы',
            'pageUrl' => 'Ссылка страницы',
            'pageTitle' => 'Название',
            'pageFullTitle' => 'Полное название',
            'pageContentShort' => 'Краткое описание',
            'pageContentFull' => 'Полное содержимое',
            'pageDescription' => 'Дополнительная информация',
            'pageImages' => 'Изображения',
            'pageActive' => 'Включена ли страница',
            'pageAuthor' => 'Редактор',
            'pageSort' => 'Сортировка',
            'pageAction' => 'Модуль',
            'pageSource' => 'ID из старой БД',
            'pageItemId' => 'Регион'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
// @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('"pageId"', $this->pageId);
        $criteria->compare('"pageParent"', $this->pageParent);
        $criteria->compare('"pageType"', $this->pageType, true);
        $criteria->compare('"pageUrl"', $this->pageUrl, true);
        $criteria->compare('"pageTitle"', $this->pageTitle, true);
        $criteria->compare('"pageContentShort"', $this->pageContentShort, true);
        $criteria->compare('"pageContentFull"', $this->pageContentFull, true);
        $criteria->compare('"pageDescription"', $this->pageDescription, true);
        $criteria->compare('"pageImages"', $this->pageImages, true);
        $criteria->compare('"pageActive"', $this->pageActive);
        $criteria->compare('"pageAuthor"', $this->pageAuthor, true);
        $criteria->compare('"pageSort"', $this->pageSort);
        $criteria->compare('"pageAction"', $this->pageAction, true);
        $criteria->compare('"pageSourceId"', $this->pageSourceId);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Page the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function beforeSave() {

        if (parent::beforeSave()) {
//			if ($this->isNewRecord)
//				$this->pageCreateDate = strtotime($this->pageCreateDate) ;
            if (array_key_exists($this->pageAction, $this->actions))
                $this->pageAction = $this->actions[$this->pageAction];
            $uploadedFile = CUploadedFile::getInstance($this, 'pageImages');
            if ($uploadedFile !== NULL) {
                if (!$this->isNewRecord) {
                    if (file_exists("uploads/images/" . $this->pageType . "/" . $this->pageImages) && !empty($this->pageImages)) {
                        unlink("uploads/images/" . $this->pageType . "/" . $this->pageImages);
                        mTools::clearThumbImages(mTools::findFile('uploads/images/' . $this->pageType . '/thumbs/', pathinfo($file, PATHINFO_FILENAME), 'jpg'));
                    }
                }
                $newFileName = getUrl::cleanString(str_replace("/", "-", $this->pageUrl)) . '.' . pathinfo($uploadedFile->name, PATHINFO_EXTENSION);
                copy($uploadedFile->tempName, 'uploads/images/' . $this->pageType . '/' . $newFileName);
                $this->pageImages = $newFileName;
            }
            if (isset($_POST['pageTitle']))
                $this->pageLinkedServices = CHtml::encode(serialize($_POST['pageTitle']));

            if ($this->pageType == 'servcenter') {

                $this->pageDescription = $_POST['brands'];
            }
            return true;
        }
        return FALSE;
    }

    protected function afterSave() {
        if ($this->isNewRecord && $this->pageType == 'model') {
            $sql = 'SELECT * FROM mb_modelsview WHERE (model_claris_id is null OR model_claris_id = -1) order by modelid desc limit 10;';
            $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
            foreach ($models as $model) {
                $url = 'http://erp.mobi03.ru/6878/model.ashx?modelName=' . urlencode($model['model']) . '&brandName=' . urlencode($model['brand']) . '&typeOId=' . $model['cat_claris_id'] . '&model_url=' . $model['url'] . '&model_id=' . $model['modelid'];
                $out = Yii::app()->curl->get($url);
                $out = json_decode($out, true);
                if (isset($out['response']) && $out['response'] == 'success') {
                    $modelOid = $out['modelOId'];
                    $brandOId = $out['brandOId'];
                } else {
                    $modelOid = -1;
                    $brandOId = -1;
                }
                $sql = 'UPDATE mb_pages SET "pageClarisOId" = ' . $modelOid . ' WHERE "pageId"=' . $model['modelid'];
                Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
                $sql = 'UPDATE mb_pages SET "pageClarisOId" = ' . $brandOId . ' WHERE "pageId"=' . $model['brandid'];
                Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
                usleep(1000);
            }
        }
    }

    protected function afterDelete() {
        parent::afterDelete();
        $file = 'uploads/images/' . $this->pageType . '/' . $this->pageImages;
        if (file_exists('uploads/images/' . $this->pageType . '/' . $this->pageImages) && !empty($this->pageImages)) {
            unlink($file);
            mTools::clearThumbImages(mTools::findFile('uploads/images/' . $this->pageType . '/thumbs/', pathinfo($file, PATHINFO_FILENAME), 'jpg'));
        }
    }

}
